package org.kyw.pet.controller;

import org.kyw.basic.exception.BusinessException;
import org.kyw.basic.util.AjaxResult;
import org.kyw.basic.util.LoginContext;
import org.kyw.basic.util.PageList;
import org.kyw.pet.domain.Pet;
import org.kyw.pet.query.PetQuery;
import org.kyw.pet.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;

    @PostMapping
    public PageList<Pet> queryPage(@RequestBody PetQuery query, HttpServletRequest request){
        return petService.queryPage(query);
    }

    @PostMapping("/onsale")
    public AjaxResult onSale(@RequestBody List<Long> ids){
        try {
            petService.onSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e){
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("报错了，正在殴打程序员");
        }
    }

    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids){
        try {
            petService.offSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e){
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("报错了，正在殴打程序员");
        }
    }

    @GetMapping("/{id}")
    public Pet queryById(@PathVariable("id") Long id){
        return petService.queryByIdDetail(id);
    }

    @GetMapping("/adopt/{id}")
    public AjaxResult adopt(@PathVariable("id") Long id,HttpServletRequest request){
        petService.adpot(id, LoginContext.getCurrentLogin(request));
        return AjaxResult.me();
    }
}
